# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : __new__单例模式(加锁)(配置管理器).py
# @Author: dongguangwen
# @Date  : 2025-03-29 21:53
import time
import threading


class Singleton:
    _lock = threading.Lock()
    __instance = None

    def __new__(cls, *args, **kwargs):
        with cls._lock:
            if not cls.__instance:
                cls.__instance = super().__new__(cls)
        return cls.__instance


class ConfigManager(Singleton):
    def __init__(self, config_file='config.ini'):
        if not hasattr(self, 'loaded'):
            self.config = self._load_config(config_file)
            self.loaded = True

    @staticmethod
    def _load_config(file):
        # 读取配置文件的逻辑
        time_ = f'time:{time.time()}'
        return {'config': time_}


def run_conf():
    conf = ConfigManager()
    print(conf.config)


if __name__ == '__main__':
    start_time = time.time()
    # 所有模块使用同一配置
    for i in range(20000):
        t = threading.Thread(target=run_conf)
        t.start()
    print('耗时：', time.time() - start_time)

    config1 = ConfigManager()
    time.sleep(2)
    config2 = ConfigManager()
    # assert config1 is config2  # True
    print(config1 is config2)
    print(config1.config)
    print(config2.config)

"""
True
{'config': 'time:1743258460.7154438'}
{'config': 'time:1743258460.7154438'}
"""

"""
并发环境下可能创建多个实例。
"""